#include "tailor.h"
#include "qdebug.h"

Tailor::Tailor(QObject *parent)
    : QObject{parent}
{

}

void Tailor::coordinates(const double &pictureW, const double &x, const double &y, const double &w, const double &h)
{
    // 将URL格式的路径转换为标准文件路径
    if (m_url.startsWith("file:///")) {
        m_url = m_url.mid(8);  // 移除前缀 "file:///"
    }
    if (m_url.startsWith("qrc:")) {
        m_url = m_url.mid(3);  // 移除前缀 "qrc:"
    }
    //QImage适合对图片的处理 QPixmap适合显示
    QImage image(m_url);
    if (image.isNull()){
        qDebug() << "Failed to load image.";
        return;
    }

    double scaling = image.width() / pictureW;
    QRect cropRect(x * scaling, y * scaling, w * scaling, h * scaling);
    QImage croppedPixmap = image.copy(cropRect);

    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    croppedPixmap.save(&buffer, "JPG");  // 可以选择其他格式如"JPG"

    emit accomplish(byteArray);
}

QString Tailor::url() const
{
    return m_url;
}

void Tailor::setUrl(const QString &newUrl)
{
    if (m_url == newUrl)
        return;
    m_url = newUrl;
    emit urlChanged();
}
